<template>
    <div>
        <m-table :columns="columns" :title="$route.meta.title" :data="companyList" :loading="loading">
            <template #extra>
                <a-button v-perms="['/adminapi/system.organize.company/save']" type="primary" shape="round" @click="handleEdit('add')">
                    <template #icon>
                        <icon-plus />
                    </template>
                </a-button>
            </template>

            <template #action="{ record }">
                <a-space>
                    <a-button v-perms="['/adminapi/system.organize.company/update']" type="primary" shape="round" @click="handleEdit('edit', record)">
                        <template #icon>
                            <icon-edit />
                        </template>
                    </a-button>

                    <a-popconfirm :content="`确定删除 [${record.name}] 吗？`" @ok="handleDelete(record.id)">
                        <a-button v-perms="['/adminapi/system.organize.company/delete']" shape="round" type="primary" status="danger">
                            <template #icon>
                                <icon-delete />
                            </template>
                        </a-button>
                    </a-popconfirm>
                </a-space>
            </template>
        </m-table>

        <EditPopup ref="editPopupRef" @success="run" />
    </div>
</template>

<script setup lang="ts">
import { getCompanyList, deleteCompany } from '@/api/system/organize/company'
import { useRequest } from 'vue-request'
import EditPopup from './components/edit.vue'
const editPopupRef = ref<InstanceType<typeof EditPopup>>()
const { data: companyList, loading, run } = useRequest(getCompanyList, {
    manual: true
})

onMounted(() => {
    run()
})

const handleEdit = (mode: 'add' | 'edit', record?: any) => {
    editPopupRef.value?.open(mode)
    if (record) {
        nextTick(() => {
            editPopupRef.value?.setFormData(record)
        })
    }
}

const handleDelete = async (id: number) => {
    try {
        console.log(id)
        await deleteCompany(id)
        run({})
    } catch (error) {
        console.error(error)
    }
}

const columns = [
    {
        title: '名称',
        dataIndex: 'name'
    },
    {
        title: '操作',
        dataIndex: 'action',
        slotName: 'action',
        width: 100
    }


]
</script>
